﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CrmContacto.Contracts;
using CrmContacto.Data;
using CrmContacto.Contracts.Enums;
using CrmContacto.Contracts.Contracts;
using CrmContacto.Contracts.Contracts.Search;
using Web.Framework.Svc;
using Web.Framework.Translate;
using CrmContacto.Services.Marketing;

namespace CrmContacto.Services.Common
{
    public class ListsCrm
    {
        public static string PrepareForSearch(string searchTerm)
        {
            searchTerm = searchTerm.ToLower();

            searchTerm = searchTerm.Replace("á", "a");
            searchTerm = searchTerm.Replace("é", "e");
            searchTerm = searchTerm.Replace("í", "i");
            searchTerm = searchTerm.Replace("ó", "o");
            searchTerm = searchTerm.Replace("ú", "u");

            return searchTerm;
        }

        public static List<CompanyConfiguration> GetCompanyConfigurations()
        {
            using (CrmContactoEntities ctxCrm = new CrmContactoEntities())
            {
                return (from e in ctxCrm.DbEmpresas
                        orderby e.Nombre
                        select new CompanyConfiguration()
                        {
                            CompanyId = e.Id,
                            CssFilePath = e.CssFilePath,
                            LogoImgFilePath = e.LogoImgFilePath
                        }).ToList();
            }
        }

        public static Dictionary<string, string> GetCompanyConfigurationKeyValues(int companyId)
        {
            using (CrmContactoEntities ctxCrm = new CrmContactoEntities())
            {
                var configurations = (from e in ctxCrm.DbEmpresaConfigurations
                                      where e.EmpresaId == companyId
                                      select new
                                      {
                                          configKey = e.ConfigKey,
                                          configValue = e.ConfigValue
                                      }).ToList();

                Dictionary<string, string> dictionary = new Dictionary<string, string>();

                foreach (var kv in configurations)
                {
                    dictionary.Add(kv.configKey, kv.configValue);
                }

                return dictionary;
            }
        }

        public static List<MaestroBase> GetCampaniasActivas(CampaniasActivasSearch search)
        {
            using (CrmContactoEntities ctxCrm = new CrmContactoEntities())
            {
                //return new List<MaestroBase>();
                DateTime now = DateTime.Now;

                IQueryable<DbAccionDeMarketing> query = ctxCrm.DbAccionDeMarketings.FilterLogicalRemoved();

                query = query.Where(a => a.PlanDeMarketing.EmpresaId == search.EmpresaId);
                
                query = query.Where(a => a.FechaDesde.HasValue && a.FechaDesde.Value <= now);
                query = query.Where(a => a.FechaHasta.HasValue && a.FechaHasta.Value >= now);

                query = query.Where(a => ctxCrm.DbAccionDeMarketingPromocions.Select(p => p.Id).Contains(a.Id));

                query = query.Where(a => a.Estado != (int)EstadoPlanDeMarketing.Cancelado && a.Estado != (int)EstadoPlanDeMarketing.Finalizado);
                query = query.Where(a => a.PlanDeMarketing.Estado != (int)EstadoPlanDeMarketing.Cancelado && a.PlanDeMarketing.Estado != (int)EstadoPlanDeMarketing.Finalizado);
                query = query.Where(a => a.CodigoParaPDV != "");
                query = query.Where(a => !a.PlanDeMarketing.Removed);

                if (search.PtoVtaId.HasValue)
                {
                    query = query.Where(a => a.PuntoDeVentas.Count == 0 || (a.PuntoDeVentas.Count > 0 && a.PuntoDeVentas.Select(p => p.Id).Contains(search.PtoVtaId.Value)));
                }

                List<DbAccionDeMarketing> accionesDeMarketing = query.ToList();                            
                var promociones = MarketingPromocionesManager.Instance.GetPromocionesVigentes(search.EmpresaId);

                List<DbAccionDeMarketing> accionesDeMarketingARemover = new List<DbAccionDeMarketing>();
                foreach (var dbAccion in accionesDeMarketing)
                {
                    if (!String.IsNullOrEmpty(dbAccion.AccionDeMarketingPromocion.TipoImplementacion))
                    {
                        var promocion = promociones.Where(p => p.Nombre == dbAccion.AccionDeMarketingPromocion.TipoImplementacion).SingleOrDefault();
                        if (promocion != null)
                        {
                            bool filtrarPromocion = promocion.FiltrarPromocionEnPdv(ctxCrm, dbAccion, search);
                            if (filtrarPromocion)
                            {
                                accionesDeMarketingARemover.Add(dbAccion);
                            }
                        }
                    }
                }

                foreach (var accionARemover in accionesDeMarketingARemover)
                {
                    accionesDeMarketing.Remove(accionARemover);
                }

                return accionesDeMarketing.Select(a => new MaestroBase() { Id = a.Id, Nombre = a.CodigoParaPDV, EmpresaId = search.EmpresaId }).ToList();              
            }
        }

        public static List<MaestroBase> GetPuntosDeVenta(int empresaId)
        {
            using (CrmContactoEntities ctxCrm = new CrmContactoEntities())
            {
                var list = (from c in ctxCrm.DbPuntoDeVentas.FilterLogicalRemoved()
                            where c.EmpresaId == empresaId
                            orderby c.Nombre
                            select c).ToList();

                return list.Select(e => new MaestroBase() { Id = e.Id, Nombre = string.Format("{0} ({1})", e.Nombre, e.CodigoExterno) }).ToList();
            }
        }

        public static List<MaestroBase> GetTipoDocumento(int paisId)
        {
            using (CrmContactoEntities ctxCrm = new CrmContactoEntities())
            {
                if (paisId != 0)
                {
                    return (from c in ctxCrm.DbTipoDocumentoes.FilterLogicalRemoved()
                            where c.PaisId == paisId
                            orderby c.Nombre
                            select new MaestroBase()
                            {
                                Id = c.Id,
                                Nombre = c.Nombre
                            }).ToList();
                }
                else
                {
                    return (from c in ctxCrm.DbTipoDocumentoes.FilterLogicalRemoved()
                            orderby c.Nombre
                            select new MaestroBase()
                            {
                                Id = c.Id,
                                Nombre = c.Nombre
                            }).ToList();
                }
            }
        }       

        public static List<MaestroBase> GetProvincias(int paisId)
        {
            using (CrmContactoEntities ctxCrm = new CrmContactoEntities())
            {
                var list = (from c in ctxCrm.DbProvincias.FilterLogicalRemoved()
                        where c.PaisId == paisId
                        orderby c.Nombre
                        select new MaestroBase()
                        {
                            Id = c.Id,
                            Nombre = c.LocalizationKey
                        }).ToList();

                list.ForEach(l => l.Nombre = LocalizationProvider.Instance[l.Nombre]);

                return list;
            }
        }

        public static List<MaestroBase> GetCategoriasDeContacto(MaestroBaseSearch searchMaestroBase)
        {
            using (CrmContactoEntities ctxCrm = new CrmContactoEntities())
            {
                IQueryable<DbCategoria> query = ctxCrm.DbCategorias.FilterLogicalRemoved();

                if (searchMaestroBase.Id.HasValue)
                {
                    query = query.Where(m => m.Id == searchMaestroBase.Id.Value);
                }
                else
                {
                    query = query.Where(e => e.EmpresaId == searchMaestroBase.EmpresaId);
                    if (!String.IsNullOrEmpty(searchMaestroBase.NombreLike))
                    {
                        query = query.Where(e => e.Nombre.Contains(searchMaestroBase.NombreLike));
                    }
                }

                return (from c in query
                        select new MaestroBase()
                        {
                            Id = c.Id,
                            Nombre = c.Nombre
                        }).ToList();
            }
        }

        public static List<MaestroBase> GetListasDeDistribucion(int empresaId)
        {
            using (CrmContactoEntities ctxCrm = new CrmContactoEntities())
            {
                return (from c in ctxCrm.DbListaDistribucions.FilterLogicalRemoved()
                        where c.EmpresaId == empresaId
                        orderby c.Nombre
                        select new MaestroBase()
                        {
                            Id = c.Id,
                            Nombre = c.Nombre
                        }).ToList();
            }
        }
    }
}
